package cn.wolfcode.trip.base.util;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * 文件上传工具
 */
public class UploadUtil {
    public static final String PATH = "D:/trip";
	//七牛云域名
	public static final String QINIU_PATH = "http://plbn87127.bkt.clouddn.com/";
	/**
	 * 处理文件上传
	 * @param file
	 * @param basePath      
	 * @return  123.png
	 */
	public static String upload(MultipartFile file, String basePath) {
		//随机字符串，用于作为保存时的文件名
		String uuid = UUID.randomUUID().toString();
		//获取文件原名
		String orgFileName = file.getOriginalFilename();
		//获取文件名的拓展名
		String ext= "." + FilenameUtils.getExtension(orgFileName);
		//新的文件保存名
		String fileName = uuid + ext;
		try {
			//最终文件对象
			File targetFile = new File(basePath, fileName);
			//把前端传入文件写入最终文件对象
			FileUtils.writeByteArrayToFile(targetFile, file.getBytes());
            //返回相对路径地址
			return "/upload/" + fileName;

		} catch (IOException e) {
			e.printStackTrace();
		}
		return "";
	}


	/**
	 * 上传到七牛云
	 * @param file
	 * @return
	 */
	public static String uploadQiniu(MultipartFile file) {
		//构造一个带指定Zone对象的配置类
		Configuration cfg = new Configuration(Zone.zone2());
		//...其他参数参考类注释
		UploadManager uploadManager = new UploadManager(cfg);
		//...生成上传凭证，然后准备上传
		String accessKey = "Fco2zOrKjSCryCg1REWfzDbthPGjXMhTtOvDuc_u";
		String secretKey = "ls98ito2uBglBmLLDJo3aiqLpVshUinQp4q6bQb6";
		String bucket = "trip";
		//默认不指定key的情况下，以文件内容的hash值作为文件名
		String key = null;//上传到服务器的文件名称(uuid)
		Auth auth = Auth.create(accessKey, secretKey);
		String upToken = auth.uploadToken(bucket);
		try {
			Response response = uploadManager.put(file.getBytes(), key, upToken);
			//解析上传成功的结果
			DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
			System.out.println(putRet.key);//文件名称
			System.out.println(putRet.hash);
			return QINIU_PATH+putRet.key;
		} catch (QiniuException ex) {
			Response r = ex.response;
			System.err.println(r.toString());
			try {
				System.err.println(r.bodyString());
			} catch (QiniuException ex2) {
				//ignore
			}
		} catch (IOException e) {
			e.printStackTrace();
		}


		return null;
	}

	
}
























